﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DuBaiCoffee2.Model
{
    public class PwebSockets
    {
        private static PwebSockets instance;
        private PwebSockets() { }
        public static PwebSockets Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new PwebSockets();
                }
                return instance;
            }
        }
        /// <summary>
        /// 其他东西的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        /// <summary>
        /// 是否可以打印
        /// </summary>
        public static bool isPrinter = false;
        public static bool isPrinterOver = false;
        /// <summary>
        /// 收到消息
        /// </summary>
        public static bool IsReviecePrinter = false;
        /// <summary>
        /// 错误信息
        /// </summary>
        public static string ErrorMsg = "";
        public static bool isPrinterSocket = false;
        public static PrinterWebSocket pSocketClient = null;// new PrinterWebSocket("ws://" + IPorPortInfo.Instance.PrinterCoffeeIP + ":" + IPorPortInfo.Instance.PrinterCofferPort);

        /// <summary>
        /// PING 通 IP
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool PingIP(string IP)
        {
            try
            {
                if (IP.Split('.').Count() < 4) return false;
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send(IP, 120);//第一个参数为ip地址，第二个参数为ping的时间
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    //ping不通
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        public void Printer_Thr()
        {
            try
            {
                if (!PingIP(IPorPortInfo.Instance.PrinterCoffeeIP))
                {
                    Thread.Sleep(100);
                    Printer_Thr();
                    return;
                }
                Pwebsocket();
                //  Heart();
            }
            catch (Exception)
            {
                Printer_Thr();
            }
        }
        public void DyCX()
        {
            try
            {
                using (var cvt = new JmPrint.Converter(JmPrint.PrinterType.Color, "revert=0:duplex=120"))
                {
                    using (var usbmgr = new USB.Manager())
                    {
                        var dd = usbmgr.Open(0);
                        try
                        {
                            var dd3 = usbmgr.GetStatus2(0xF4, 4);
                            Console.WriteLine(dd3.Count());
                            if (dd3.Count() > 3)
                            {
                                var msg = dd3[0] + " " + dd3[1] + " " + dd3[2] + " " + dd3[3];
                                Console.WriteLine(dd3[0] + " " + dd3[1] + " " + dd3[2] + " " + dd3[3]);
                                if (msg == "8 0 0 0" || msg == "9 0 0 0")
                                {
                                    WuLiaoCoffeeSel.Instance.Print_Bol = true;
                                }
                                else
                                {
                                    WuLiaoCoffeeSel.Instance.Print_Bol = false;
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                        usbmgr.Close();
                        Console.WriteLine("ending");
                    }

                }
            }
            catch (Exception)
            {

            }
        }
        public int Init = 0;
        public void DyCS(string path)
        {
            try
            {
                using (var cvt = new JmPrint.Converter(JmPrint.PrinterType.Color, "revert=0:duplex=120"))
                {
                    var imgPath = path;
                    cvt.ConvertImage(imgPath, 600, 600);
                    var data = cvt.GetData();
                    using (var usbmgr = new USB.Manager())
                    {
                        try
                        {
                            var dd = usbmgr.Open(0);
                            var dd2 = usbmgr.Write(data);
                        }
                        catch (Exception)
                        {
                        }
                        try
                        {
                            Thread.Sleep(15000);
                            while (true)
                            {
                                var dd3 = usbmgr.GetStatus2(0xF4, 4);
                                Console.WriteLine(dd3.Count());
                                if (dd3.Count() > 3)
                                {
                                    var msg = dd3[0] + " " + dd3[1] + " " + dd3[2] + " " + dd3[3];
                                    Console.WriteLine(dd3[0] + " " + dd3[1] + " " + dd3[2] + " " + dd3[3]);
                                    if (msg == "8 0 0 0")
                                    {
                                        break;
                                    }
                                }
                                //Init++;
                                //if (Init == 60)
                                //{
                                //    break;
                                //}
                                Thread.Sleep(1000);
                            }
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(15000);
                        }
                        usbmgr.Close();
                        Thread.Sleep(4000);
                        Console.WriteLine("ending");
                    }

                }
            }
            catch (Exception)
            {
            }
        }
        public static void Pwebsocket()
        {
#pragma warning disable CS0168 // 声明了变量，但从未使用过
            try
            {
                pSocketClient = new PrinterWebSocket("ws://" + IPorPortInfo.Instance.PrinterCoffeeIP + ":" + IPorPortInfo.Instance.PrinterCofferPort);
                pSocketClient.OnOpen -= PSocketClient_OnOpen;
                pSocketClient.OnMessage -= PSocketClient_OnMessage;
                pSocketClient.OnClose -= PSocketClient_OnClose;
                pSocketClient.OnError -= PSocketClient_OnError;
                pSocketClient.OnOpen += PSocketClient_OnOpen;
                pSocketClient.OnMessage += PSocketClient_OnMessage;
                pSocketClient.OnClose += PSocketClient_OnClose;
                pSocketClient.OnError += PSocketClient_OnError;
                pSocketClient.Open();
                Thread.Sleep(1000);
                isPrinterSocket = true;
            }
            catch (Exception ex)
            {
                pSocketClient.Close();
                Thread.Sleep(4000);
                pSocketClient.OnOpen -= PSocketClient_OnOpen;
                pSocketClient.OnMessage -= PSocketClient_OnMessage;
                pSocketClient.OnClose -= PSocketClient_OnClose;
                pSocketClient.OnError -= PSocketClient_OnError;
                Pwebsocket();
                return;
            }
#pragma warning restore CS0168 // 声明了变量，但从未使用过
        }
        private static void PSocketClient_OnError(object sender, Exception ex)
        {

        }

        private static void PSocketClient_OnClose(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 打印机状态变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private static void PSocketClient_OnMessage(object sender, string data)
        {
            //处理的消息错误将会忽略
#pragma warning disable CS0168 // 声明了变量，但从未使用过
            try
            {

                var json = JsonConvert.DeserializeObject<PrinterMessageModel>(data);//Ready
                Console.WriteLine(data);
                if (json != null)
                {
                    switch (json.code)
                    {
                        //查询机器状态
                        case 1:
                            IsReviecePrinter = true;
                            switch (json.tag)
                            {
                                case 0:
                                    pSocketClient.Send(JsonConvert.SerializeObject(new PrinterSel { code = 1, tag = 0 }));
                                    break;
                                case 1:
                                case 2:
                                    isPrinter = true;
                                    break;
                                case 3:
                                    break;
                                case 4:
                                    break;
                                case 5:
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 2:
                            isPrinter = false;
                            Console.WriteLine(data + "123123132");
                            switch (json.tag)
                            {
                                case 1:
                                case 4:
                                case 5:
                                case 6:
                                case 7:
                                    ErrorMsg = "ok";
                                    break;
                                case 2:
                                    ErrorMsg = "ok1"; ///"杯子尺寸使用不正确";
                                    break;
                                case 3:
                                    ErrorMsg = ""; //"图片处理数据失败";
                                    break;
                                case 11:
                                    ErrorMsg = "ok1";// "打印失败，托盘卡住";
                                    break;
                                case 8:
                                    ErrorMsg = "over";
                                    var Printer_Sel = new PrinterSel { code = 1, tag = 1 };
                                    pSocketClient.Send(JsonConvert.SerializeObject(Printer_Sel));
                                    break;
                                case 9:
                                    ErrorMsg = "ok1";// "打印失败，打印超时";
                                    break;
                                case 10:
                                    ErrorMsg = "ok1";// "打印失败，没有检测到杯子";
                                    break;
                                default:
                                    break;
                            }
                            break;
                        default:
                            break;
                            //case 3:
                            //    var Msg = JsonConvert.DeserializeObject<feedBackMsg>(json.data.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(data + "123123132789798");
                return;
            }
#pragma warning restore CS0168 // 声明了变量，但从未使用过

        }

        private static void PSocketClient_OnOpen(object sender, EventArgs e)
        {

        }
    }
}
